<template>
  <div class="page-container">
    <DynamicForm class="mt-4" :config="dyConfig" :questions="dyQuestions" />
    <DynamicTable :tables="dyTable" :config="dyTableConfig" :icons="dyIcons" ref="directoryRef" @onSelectChange="selectcheckbox" />
  </div>
</template>

<script lang="ts" setup>
import { DynamicForm, DynamicTable } from '@/components/public-template';
import { HOST } from '@/config';
import { Api, advancedQueryPreview, advancedQueryArchivesTypeTree, advancedQueryBatchDownload, normalPreview, normalDownload } from '@/config/api/searchManage';
import { useUserStoreWithOut } from '@/store/modules/user';
import { filter } from 'rxjs/operators';
import { getCurrentInstance, onBeforeUnmount, onMounted, reactive, ref } from 'vue';
import indexService from './index.service';
import { downloadFile } from '@/utils/useDownload';
import { SUB_SYSTEM } from '@/enums/commonEnum';
import { Modal, message } from 'ant-design-vue';
import { useRouter } from 'vue-router';

const { proxy }: any = getCurrentInstance();
const accessToken = useUserStoreWithOut().getToken;

const directoryRef = ref(null);
const router = useRouter();

const dyQuestions = reactive(indexService.getQuestions());
const dyConfig: any = {
  labelCol: 6,
  wrapperCol: 18,
  grid: 8,
  style: 'table-form',
  cancelSave: true,
  combinationMethod(msg) {
    dyTableConfig.queryUrl = Api.normalRecordPage;
    dyTableConfig.params = { ...msg };
    directoryRef.value.getData();
  }
};

const dyTable = reactive(indexService.getTables());
const dyIcons = reactive(indexService.getIcons());
const dyTableConfig: any = {
  queryUrl: Api.normalRecordPage,
  protType: 'post',
  scroll: { x: 1500, y: 540 },
  isScreen: true,
  isPagingLocalData: true,
  rowSelection: { type: 'checkbox' }
};

const state = reactive({});

const subscribeSub = proxy.$NotificationPubSub
  .getParams()
  .pipe(filter((res) => res !== 0))
  .subscribe((item: any) => {
    if (item.key === 'DYNAMICLOCALTABLE' && item.value.part?.text === '预览') {
      normalPreview({ id: item.value.data?.id, needRecord: true }).then((result) => {
        if (result && result.success) {
          window.open(result.data);
        }
      });
    } else if (item.key === 'DYNAMICLOCALTABLE' && item.value.part?.text === '下载') {
      const url = `${Api.normalDownload}/${item.value.data.id}`;
      downloadFile(url);
    } else if (item.key === 'DYNAMICLOCALICONS' && item.value.value === '下载') {
      // 上方按钮-批量下载
      if (item.state.selected.length) {
        let idArr: Array<String> = []; // id多选
        for (let i of item.state.selected) {
          idArr.push(i.id);
        }
        const xhr = new XMLHttpRequest();
        xhr.open('POST', `${HOST}${Api.normalBatchDownload}`, true);
        xhr.setRequestHeader('token', accessToken);
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.responseType = 'blob';
        xhr.onload = function () {
          if (this.status == 200) {
            const blob = new Blob([this.response], { type: 'contentType' });
            const contentDisposition = xhr.getResponseHeader('content-disposition');
            let filename = contentDisposition.substring(contentDisposition.indexOf('filename')).replace(/"/gi, '');
            filename = window.decodeURIComponent(filename.substring(filename.indexOf('=') + 1));
            const a = document.createElement('a');
            a.href = window.URL.createObjectURL(blob);
            a.download = filename;
            a.click();
            window.URL.revokeObjectURL(Api.advancedQueryBatchDownload);
          }
        };
        xhr.send(JSON.stringify({ ids: idArr }));
      } else {
        message.warn('请先选中一个选项');
      }
    } else if (item.key === 'DYNAMICLOCALICONS' && item.value.value === '借阅') {
      console.log(item.state.selected, 333);

      const arr = item.state.selected.map((item) => {
        if (!item.isBorrowing) {
          return item.id;
        }
      });
      router.push({ name: 'ArchivesManageAddBorrow', query: { showType: 'ADD', ids: arr } });
    }
  });

onMounted(() => {});

const selectcheckbox = (oldSelectedRows) => {
  console.log(oldSelectedRows, 'oldSelectedRows');
  // 只要勾选上了不能下载的的就禁用多选下载
  const boolean = oldSelectedRows[1].every((item) => {
    return item.couldDownload == true;
  });
  console.log(boolean, 'boolean');
  dyIcons.forEach((item) => {
    if (item.value == '下载') item.disabled = !boolean;
  });
};

onBeforeUnmount(() => {
  subscribeSub && subscribeSub.unsubscribe();
  proxy.$NotificationPubSub.clearParams();
});
</script>

<style lang="less" scoped></style>
